package tgc.edu.yzy.cocApi.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

import javax.imageio.ImageIO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.forte.qqrobot.utils.BaseLocalThreadPool;

import tgc.edu.yzy.cocApi.custom.CocApiAndCqCustom;
import tgc.edu.yzy.cocApi.custom.ImageClanAll;
import tgc.edu.yzy.cocApi.entity.Clans.PlayleTroops;
import tgc.edu.yzy.cocApi.entity.image.ImagePlayersFrom;
import tgc.edu.yzy.custom.Https;
import tgc.edu.yzy.custom.QRCodeUtil;
import tgc.edu.yzy.custom.TimeUtils;

public class PlayersService {

	/***
	 * 获取网络图片
	 * @param play
	 * @return
	 * @throws IOException 
	 */
	public ImagePlayersFrom TagData(JSONObject play){
		ImagePlayersFrom form = new ImagePlayersFrom();
		Executor threadPool = BaseLocalThreadPool.getThreadPool();
		
		//获取玩家得个性标签
		JSONArray jsonArray = play.getJSONArray("labels");
		Integer Count_Labels = 0;
		if(jsonArray!=null) {
			Count_Labels = jsonArray.size();
		}
		CountDownLatch scount = new CountDownLatch(3+Count_Labels);//专门为获取部落图片开启的线程 ，最后关闭
		
		
		//查询玩家是否有部落 获取部落标签
		JSONObject jsonObject = play.getJSONObject("clan");
		if(jsonObject!=null) {
			String CLAN_tag = jsonObject.getString("tag");
			String tag = CLAN_tag.substring(1, CLAN_tag.length());
			
			BufferedImage Clan_Image = null;//ImageClanAll.buffer.get("badgeUrls"+tag);
			String string = ImageClanAll.ggmap.get("badgeUrls"+tag);
			if(string!=null) {
				Clan_Image = CocApiAndCqCustom.getImage("badgeUrls"+tag);
			}
			//BufferedImage Clan_Image = ImageClanAll.buffer.get("badgeUrlsClan");
			form.setClanName(jsonObject.getString("name"));
			form.setClanTag(CLAN_tag);
			//21级 | 首领	用来显示玩家在部落的信息
			form.setClanClanLevel(jsonObject.getString("clanLevel")+"级 | "+CocApiAndCqCustom.CocRole(play.getString("role")));
			if(Clan_Image==null) {
				JSONObject CLAN_badgeUrls = play.getJSONObject("clan").getJSONObject("badgeUrls");
				if(CLAN_badgeUrls!=null) {
					String badgerUrlslarge = CLAN_badgeUrls.getString("small");
					threadPool.execute(()->{
						try {
							BufferedImage httpsGet = Https.httpsGet(badgerUrlslarge, null);
							ImageClanAll.ggmap.save("badgeUrls"+tag, badgerUrlslarge, TimeUtils.endMin(120));
							ImageIO.write(httpsGet, "png", new File("C:\\cocutil\\ClanAll\\badgeUrls"+tag+".png"));
							form.setClan(httpsGet);
							System.out.println("获取成功：部落标签");
						} catch (Exception e) {
							System.out.println("玩家图获取部落标签获取部落片失败!");
						}
						scount.countDown();
					});
				}else {
					scount.countDown();
				}
			}else {
				form.setClan(Clan_Image);
				scount.countDown();
			}
		}else {//当无部落时。直接断掉
			scount.countDown();
		}
		/***
		 * 	玩家个性标签
		 */
		List<BufferedImage> Labels_List = new ArrayList<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			//获取标签ID
			String labels_Id = jsonArray.getJSONObject(i).getString("id");
			//图片地址
			String Labels_URL = jsonArray.getJSONObject(i).getJSONObject("iconUrls").getString("small");
			threadPool.execute(()->{
				BufferedImage labels_Image = CocApiAndCqCustom.getImage("PlayersId"+labels_Id);//ImageClanAll.buffer.get("PlayersId"+labels_Id);
				if(labels_Image==null) {
					try {//C:\cocutil\matter\end
						BufferedImage httpsGet = Https.httpsGet(Labels_URL, null);
						//先把保存下来方便后期优化
						ImageIO.write(httpsGet, "png", new File("C:\\cocutil\\matter\\end\\PlayersId"+labels_Id+".png"));
						ImageClanAll.buffer.put("PlayersId"+labels_Id, httpsGet);
						Labels_List.add(httpsGet);
						System.out.println("获取成功：个性标签");
					} catch (Exception e) {
						System.out.println("生成失败！");
					}
				}else {
					Labels_List.add(labels_Image);
				}
				scount.countDown();
			});
		}
		form.setGxbq(Labels_List);
		/***
		 * 玩家杯段 
		 */
		JSONObject League_Entity = play.getJSONObject("league");
		if(League_Entity!=null) {
			String League_ID = League_Entity.getString("id");
			BufferedImage bufferedImage = CocApiAndCqCustom.getImage("Plaryleague"+League_ID);
			//BufferedImage bufferedImage = ImageClanAll.buffer.get("wubei");
			String League_URL = play.getJSONObject("league").getJSONObject("iconUrls").getString("small");
			if(bufferedImage==null&&League_URL!=null) {
				threadPool.execute(()->{
					try {
						System.out.println(League_URL);
						BufferedImage League_Image = Https.httpsGet(League_URL, null);
						ImageIO.write(League_Image, "png", new File("C:\\cocutil\\matter\\Plaryleague"+League_ID+".png"));
						form.setGrth(League_Image);
						System.out.println("获取成功：部落标签");
					} catch (IOException e) {
						form.setGrth(CocApiAndCqCustom.getImage("wubei"));
						System.out.println("获取玩家杯段失败");
					}
					scount.countDown();
				});
			}else {
				form.setGrth(bufferedImage);
				scount.countDown();
			}
		}else {
			form.setGrth(CocApiAndCqCustom.getImage("wubei"));
			scount.countDown();
		}
		
		/***
		 * 二维码
		 */
		String Play_TAG = play.getString("tag");
		if(Play_TAG!=null) {
			String PLAY_TXT = "http://yzycoc.com/qq/cocApi/playercoc?tag="+Play_TAG.substring(1, Play_TAG.length());
			threadPool.execute(()->{
				try {
					BufferedImage image = QRCodeUtil.createImage(PLAY_TXT, "C:\\cocutil\\matter\\QRcode.jpg", true);
					form.setErweima(image);
				} catch (Exception e) {
					form.setErweima(CocApiAndCqCustom.getImage("QRcode"));
				}
				scount.countDown();
			});
		}else {
			form.setErweima(CocApiAndCqCustom.getImage("QRcode"));
			scount.countDown();
		}
		
		
		/***
		 * 处理数据
		 */
		JSONArray troo = play.getJSONArray("troops");//兵种等级排序
		HashMap<String, PlayleTroops> troopsmap = new HashMap<>();
		Troops_Play(troo,troopsmap);
		JSONArray heroes = play.getJSONArray("heroes");//英雄
		Troops(heroes,troopsmap);
		JSONArray spells = play.getJSONArray("spells");//法术
		Troops(spells,troopsmap);
		
		//主世界兵种列表
		List<PlayleTroops> troops_home  = new ArrayList<>();
		for (int i = 0; i < CocApiAndCqCustom.troops_home.length; i++) {
			troops_home.add(troopsmap.get(CocApiAndCqCustom.troops_home[i]+"home"));
		}
		form.setTroops_home(troops_home);
		
		//夜世界
		List<PlayleTroops> troops_builderBase  = new ArrayList<>();
		for (int i = 0; i < CocApiAndCqCustom.troops_builderBase.length; i++) {
			troops_builderBase.add(troopsmap.get(CocApiAndCqCustom.troops_builderBase[i]+"builderBase"));
		}
		form.setTroops_builderBase(troops_builderBase);
		
		//三王
		List<PlayleTroops> sw  = new ArrayList<>();
		for (int i = 0; i < CocApiAndCqCustom.heroes.length; i++) {
			sw.add(troopsmap.get(CocApiAndCqCustom.heroes[i]));
		}
		form.setHeroes(sw);
		
		//法术
		List<PlayleTroops> fs  = new ArrayList<>();
		for (int i = 0; i < CocApiAndCqCustom.spells.length; i++) {
			fs.add(troopsmap.get(CocApiAndCqCustom.spells[i]));
		}
		form.setSpells(fs);
		
		//攻城车
		List<PlayleTroops> gcd  = new ArrayList<>();
		for (int i = 0; i < CocApiAndCqCustom.s.length; i++) {
			gcd.add(troopsmap.get(CocApiAndCqCustom.s[i]+"home"));
		}
		form.setGcd(gcd);
		
		//获取总捐兵数
		JSONArray achievements = play.getJSONArray("achievements");
		String zjbsum = "";
		for (int i = 0; i < achievements.size(); i++) {
			String name = achievements.getJSONObject(i).getString("name");
			if("Friend in Need".equals(name)) {
				zjbsum = achievements.getJSONObject(i).getString("value");
				break;
			}
		}
		//玩家个人数据 第一列数据
		List<String> play_one = new ArrayList<>();
		play_one.add(CocApiAndCqCustom.CocTownHallLevel(play.getInteger("townHallLevel"), play.getInteger("townHallWeaponLevel")));
		play_one.add("Lv."+txt(play.getString("builderHallLevel"),3));
		play_one.add(txt(play.getString("expLevel"),3));
		form.setPlay_one(play_one);
		//玩家个人数据 第二列数据
		List<String> play_two = new ArrayList<>();
		play_two.add(txt(play.getString("trophies"),3));
		play_two.add(txt(play.getString("versusTrophies"),3));
		play_two.add(txt(play.getString("warStars"),3));
		form.setPlay_two(play_two);
		//玩家个人数据 第三四列数据
		List<String> play_three = new ArrayList<>();
		play_three.add(txt(play.getString("donations"),0));
		play_three.add(txt(play.getString("donationsReceived"),0));
		play_three.add(zjbsum);
		play_three.add(txt(play.getString("attackWins"),0));
		play_three.add(txt(play.getString("defenseWins"),0));
		play_three.add(txt(play.getString("versusBattleWins"),0));
		form.setPlay_three(play_three);
		//玩家个人数据 第五列数据
		List<String> play_five = new ArrayList<>();
		play_five.add(txt(play.getString("bestTrophies"),0));
		play_five.add(txt(play.getString("bestVersusTrophies"),0));
		String legendStatistics = play.getJSONObject("legendStatistics")==null?"—":play.getJSONObject("legendStatistics").getString("legendTrophies");
		play_five.add(legendStatistics);
		form.setPlay_five(play_five);
		//主程序阻塞
		try {
			scount.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return form;
	}
	/**
	 * 	处理玩家兵种
	 * @param troo
	 * @param troopsmap 
	 */
	private static void Troops_Play(JSONArray troo, HashMap<String, PlayleTroops> troopsmap) {
		for (int i = 0; i < troo.size(); i++) {
			PlayleTroops e = new PlayleTroops();
			JSONObject troops = troo.getJSONObject(i);
			String name = troops.getString("name")+ troops.getString("village");//名称
			Integer  number= troops.getInteger("level")==null?0:troops.getInteger("level");//玩家的等级
			Integer maxLevel = troops.getInteger("maxLevel")==null?0:troops.getInteger("maxLevel");//最高等级
			if(number == maxLevel) {
				e.setMax(true);
			}else {
				e.setMax(false);
			}
			
			e.setNumber(number.toString());
			troopsmap.put(name, e);
		}
	}
	/**
	 * 	处理玩家兵种
	 * @param troo
	 * @param troopsmap 
	 */
	private static void Troops(JSONArray troo, HashMap<String, PlayleTroops> troopsmap) {
		for (int i = 0; i < troo.size(); i++) {
			PlayleTroops e = new PlayleTroops();
			JSONObject troops = troo.getJSONObject(i);
			String name = troops.getString("name");//名称
			Integer  number= troops.getInteger("level")==null?0:troops.getInteger("level");//玩家的等级
			Integer maxLevel = troops.getInteger("maxLevel")==null?0:troops.getInteger("maxLevel");//最高等级
			if(number == maxLevel) {
				e.setMax(true);
			}else {
				e.setMax(false);
			}
			e.setNumber(number.toString());
			troopsmap.put(name, e);
		}
	}
	
	public static String txt(String txt,Integer type) {
		switch (type) {
		case 1:
			return txt==null?"无":txt;
		case 0:
			return txt==null?"—":txt;
		case 2:
			return txt==null?"":txt;
		case 3:
			return txt==null?"0":txt;
		default:
			return txt==null?"":txt;
		}
		
	}
}
